﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Security;


namespace TcpServer.User
{
    class ServerClient
    {
        public DateTime LastConnTime { get; set; }
        public TcpClient Client { get; set; }
        public string UserName { get; set; }
        public Thread SerCliThread { get; set; }
        public NetworkStream NStream { get; set; }
        public byte[] buffer { get; set; }
        public int ListIndexID { get; set; }

        public ServerClient(TcpClient client)
        {
            this.Client = client;
            NStream = this.Client.GetStream();
        }

        public void Close()
        {
            
            this.Client.Close();
            NStream.Close();
            NStream.Dispose();

            try
            {
                Program.SerList.Remove(this);
                SerCliThread.Abort();
                SerCliThread.Join();
            }
            catch (ThreadAbortException ex)
            {
                Console.WriteLine("正常捕捉线程终止异常,ThreadAbortException:" + ex.Message.ToString());
                Log.Info("ServerClient", "线程ID=" + SerCliThread.ManagedThreadId.ToString() + ";正常捕捉到线程终止异常ThreadAbortException,线程退出,");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message.ToString());
                Console.WriteLine("线程停止出现问题");
                Log.Error("ServerClient", "线程ID=" + SerCliThread.ManagedThreadId.ToString() + ";线程停止出现问题:"+ex.Message.ToString());
            }
            //在此需要用倒叙方式删除相对应的引用
            
        }
        public void SendData(String data)
        {
            if (NStream.CanWrite)
            {
                byte[] WriteBuffer = Encoding.Default.GetBytes(data);
                NStream.Write(WriteBuffer, 0, WriteBuffer.Length);
            }
            else
            {
                Console.WriteLine("Sorry.  You cannot write to this NetworkStream.");
            }
        }

        public void ReciveData()
        { 
            string ReceiveData = "";
            if (NStream.CanRead)
            {
                buffer = new byte[1024];
                int count = 0;
                do
                {
                    //string ReceiveString = null;
                    //MeterIP=99,#99,10001,00111,11100,12341234,44332211,12345678,88889999*
                    //HotelID=210883,MeterIP=99,#210883,00,10001,00011,00110,116300,332211,123456,888999,8152483225296867501373643AB3863F*
                    try
                    {
                        count = NStream.Read(buffer, 0, 1024);
                        //NStream.Flush();
                        ReceiveData = Encoding.Default.GetString(buffer, 0, count);
                        
                        Console.WriteLine(ReceiveData+":Server");
                        Log.Info("ServerClient", ReceiveData+",线程ID="+SerCliThread.ManagedThreadId.ToString());
                        if (ReceiveData.Contains("HotelID"))        //这是新版本
                        {
                            string temp = ReceiveData.Substring(ReceiveData.IndexOf(',') + 1);
                            temp = temp.Substring(temp.IndexOf(',') + 1);
                            string HotelID= ReceiveData.Substring(0, ReceiveData.IndexOf(','));
                            HotelID = HotelID.Replace("HotelID=", "");


                            string MeterIP = ReceiveData.Substring(ReceiveData.IndexOf(',') + 1);
                            MeterIP = MeterIP.Substring(0, MeterIP.IndexOf(','));
                            MeterIP = MeterIP.Replace("MeterIP=", "");

                            try
                            {
                                foreach (UserClass item in Program.UserList)
                                {
                                    if (item.MeterIP == MeterIP && item.hotelID == HotelID) 
                                    {
                                        item.SendData(temp + "\r\n");
                                    }
                                }

                                //Program.UserList.Find(s => s.MeterIP.Equals(MeterIP)).SendData(temp+"\r\n");
                                LastConnTime = DateTime.Now;

                            }
                            catch (NullReferenceException)
                            {
                                Console.WriteLine("没有找到该设备在线，");
                                Log.Error("ServerClient", "没有找到设备对应的长连接:MeterIP=" + MeterIP);

                            }
                        }
                        else if (ReceiveData.Contains("MeterIP"))   //这是老版本的处理方法
                        {
                            string temp = ReceiveData.Substring(ReceiveData.IndexOf(',')+1);
                            string MeterIP = ReceiveData.Substring(0, ReceiveData.IndexOf(','));
                            MeterIP = MeterIP.Replace("MeterIP=", "");

                            try
                            {
                                foreach (UserClass item in Program.UserList)
                                {
                                    if (item.MeterIP == MeterIP)
                                    {
                                        item.SendData(temp + "\r\n");
                                    }
                                }

                                //Program.UserList.Find(s => s.MeterIP.Equals(MeterIP)).SendData(temp+"\r\n");
                                LastConnTime = DateTime.Now;

                            }
                            catch (NullReferenceException)
                            {
                                Console.WriteLine("没有找到该设备在线，");
                                Log.Error("ServerClient", "没有找到设备对应的长连接:MeterIP=" + MeterIP);

                            }
                            //Program.UserList.Find(s => s.IMEI.Equals(sArray[i].Replace("IMEI=", ""))).SendData("server Send you Message:" + sArray[i]);
                            //NStream.Flush();                            
                        }
                        //使用lambda表达式，查找List里面的东西list.Find(s => s.Name .Equals("abc") && s.Age == 15) 
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message.ToString());
                        Log.Info("ServerClient", "Close方法被调用，try-catch");
                        Close();
                        break;
                    }
                    //下面的判断为，没有可读数据，并且计数返回的是0 表示客户端有意断开了。
                } while (NStream.DataAvailable || count != 0);
            }
            Log.Info("ServerClient", "主动退出");
            Client.Close();
            NStream.Close();
            NStream.Dispose();
            Program.SerList.Remove(this);
            Console.WriteLine("ServerCMD线程退出");
            

        }


    }
}
